/*
 * Logger.cpp
 *
 *  Created on: Apr 18, 2011
 *      Author: Sergio Colinas
 */

#include "Logger.h"

#define LOG_FILE "log.txt"

Logger* Logger::m_pInstance = NULL;

Logger* Logger::Instance(bool _debug) {
	if (!m_pInstance) {
		m_pInstance = new Logger(_debug);
		//Al terminar el programa llama a DestroyInstance
		if (atexit(&DestroyInstance) != 0)
			throw "Error al intentar registrar la función que libera la memoria utilizada";
	}

	return m_pInstance;
}

void Logger::DestroyInstance() {
	if (m_pInstance)
		delete m_pInstance;
}

Logger::Logger(bool _debug) {
	this->debug = _debug;
	this->lock = new LockFile((char *) LOG_FILE, debug);
}

Logger::~Logger() {
	delete lock;
}

void Logger::writeToLogFile(string txt) {
	//Solo escribe en el log si corresponde (debug == true)
	if (this->debug) {
		try {
			lock->tomarLock(true);
			string s = Util::getAsciiTime() + " (pid = " + Util::toString(getpid()) + ") - " + txt;
			lock->escribir(s.c_str(), s.size());
			lock->liberarLock(true);
		} catch (...) {
			throw "Error al escribir en archivo de log";
		}
	}
}

